package com.dream.controller;

import java.io.File;

import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.UUID;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.dream.pojo.ArticleSon;
import com.dream.pojo.Imgjson;
import com.dream.pojo.ResourceSon;
import com.dream.service.able.All_Service_able;
import com.dream.service.able.Search_able;


@RequestMapping
@Controller
public class DreamController {

	@Resource(name="Resources_ServiceImpl")
	private All_Service_able <ResourceSon> resources_serviceImpl;

	@Resource(name="Article_Serviceimpl")
	private All_Service_able<ArticleSon> article_serviceImpl;

	@Resource(name="Article_Serviceimpl")
	private Search_able <ArticleSon> search_impl;

	@ResponseBody
	@RequestMapping("Search")
	public Object Search(){
		return article_serviceImpl.getT("1","1");
	}

	@ResponseBody
	@RequestMapping("time")
	public String  timetemp(){
		return "时间";
	}


	@ResponseBody
	@RequestMapping("listResource")
	public List <ResourceSon> listtemp(){
		return resources_serviceImpl.list();
	}

	@ResponseBody
	@RequestMapping("listArticle")
	public List <ArticleSon> listArticle(){
		return article_serviceImpl.list();
	}


	/*
	 * 图片上传的请求(富文本域)
	 */
	@ResponseBody
	@RequestMapping(value="/saveimg")
	public Imgjson fileupload(MultipartFile file,HttpServletRequest request){
		Imgjson imgjson=new Imgjson();
		if(file!=null&&file.getOriginalFilename()!=null&&file.getOriginalFilename().length()>0){
			String origName=file.getOriginalFilename();//得到文件名
			String extendsName=origName.substring(origName.lastIndexOf("."));//得到文件后缀BMP、JPG、JPEG、PNG、GIF。 BMP
			if(extendsName.equals(".bmp")||extendsName.equals(".jpg")||extendsName.equals(".jpeg")||extendsName.equals(".png")||extendsName.equals(".gif")){
				//SimpleDateFormat df = new SimpleDateFormat("yyyy年MM月dd日HH时mm分ss秒");//设置日期格式  
				String randanddate=UUID.randomUUID().toString(); // new Date()为获取当前系统时间  
				//保存路径

				String filename=this.getClass().getClassLoader().getResource("").getPath()+"../file/images/dreamimg/"+randanddate+extendsName;
				File uploadFile=new File(filename);
				try {
					System.out.println(uploadFile.getPath());
					file.transferTo(uploadFile);
					imgjson.setCode(0);//0表示没有错误
					imgjson.setMsg("提示");
					String [] Data={request.getScheme() + "://" + request.getServerName() + ":" + request.getServerPort()+"/file/images/dreamimg/"+randanddate+extendsName};
					imgjson.setData(Data);
					System.err.println("保存图片了");
					return imgjson;
				} catch (IllegalStateException | IOException e) {
					System.out.println(e.getMessage());
					imgjson.setCode(1);//1文件上传异常
					return imgjson;
				}
			}else{
				imgjson.setCode(2);//2用户上传的文件格式不正确
			}
		}else{
			imgjson.setCode(3);//3用户没有上传文件
		}
		return imgjson;
	}

	@RequestMapping("addshare")
	public String tempimg(){
		return "addshre";
	}



	@RequestMapping
	public String temp(){
		return "home";
	}




	@RequestMapping("home")
	public String getHome(){
		return "home";
	}




	public String first(String code){
		System.out.println(code);
		return "home";
	}


	@RequestMapping("first")
	@ResponseBody
	public String QQLogin(HttpServletRequest request,String expires_in) {
		String access_token=request.getParameter("access_token");
		String userUrl = "https://graph.qq.com/oauth2.0/me?access_token=" + access_token;
		String sr = httpRequest(userUrl);
		System.out.println("-----------------");
		System.out.println(sr);
		System.out.println(access_token);
		System.out.println("-----------------");
		JSONObject result = JSON.parseObject(sr.substring(10, sr.length() - 3));

		//获取Open_ID
		String openId = (String) result.get("openid");
		//根据OpenId去获取用户信息
		String userinfoUrl = "https://graph.qq.com/user/get_user_info?access_token=" + access_token +
				"&oauth_consumer_key=101514403&openid=" + openId;
		String userInfoText = httpRequest(userinfoUrl);
		JSONObject userInfoResult = JSON.parseObject(userInfoText);
		String nickName = (String) userInfoResult.get("nickname");
		String userIconUrl = (String) userInfoResult.get("figureurl");
		return nickName;
	}



	//http请求，链接url
	public static String httpRequest(String url) {
		HttpURLConnection urlConnection = null;
		String responseStr = "";
		try {
			urlConnection = (HttpURLConnection) new URL(url).openConnection();
			urlConnection.setRequestProperty("Accept-Charset", "utf-8");
			urlConnection.setRequestProperty("contentType", "utf-8");
			urlConnection.connect();
			InputStream inputStream = urlConnection.getInputStream();
			responseStr = streamToString(inputStream);
			inputStream.close();
		} catch (IOException e) {
			e.printStackTrace();
		}
		return responseStr;
	}
	public static String streamToString(java.io.InputStream is_) 
	{ 
		try{ 
			if (is_ != null) { 
				StringBuilder sb = new StringBuilder(); 
				String line; 
				try { 
					java.io.BufferedReader reader = new java.io.BufferedReader( 
							new java.io.InputStreamReader(is_,"UTF-8")); 
					while ((line = reader.readLine()) != null) { 
						sb.append(line).append("n"); 
					} 
				} finally { 
					is_.close(); 
				} 
				return sb.toString(); 
			} else { 
				return""; 
			} 
		} 
		catch( Exception ex ) { 
			return null; 
		} 
	}

}
